package storages

import (
	"github.com/pkg/errors"
	"gluenet/internal/glue-srvm/model"
	"gorm.io/gorm"
)

type hostToMachineStorage struct{}

var DefaultHostToMachineStorage = &hostToMachineStorage{}

func (c *hostToMachineStorage) Insert(db *gorm.DB, data model.MaasHostToMachine) (uint, error) {
	return uint(data.Id), errors.WithStack(db.Create(&data).Error)
}

func (c *hostToMachineStorage) Update(db *gorm.DB, filter, data model.MaasHostToMachine) error {
	return errors.WithStack(db.Model(data).Where(&filter).Updates(&data).Error)
}

func (c *hostToMachineStorage) DeleteByID(db *gorm.DB, id uint) error {
	if id == 0 {
		return errors.New("ID cannot be empty.")
	}
	return errors.WithStack(db.Delete(&model.MaasHostToMachine{Id: uint64(id)}).Error)
}

func (c *hostToMachineStorage) FindOne(db *gorm.DB, filter model.MaasHostToMachine) (*model.MaasHostToMachine, error) {
	var hostToMachine model.MaasHostToMachine
	err := db.Where(&filter).Find(&hostToMachine).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, nil
	}
	return &hostToMachine, errors.WithStack(err)
}

func (c *hostToMachineStorage) FindAll(db *gorm.DB, filter model.MaasHostToMachine) ([]model.MaasHostToMachine, error) {
	var hostToMachines []model.MaasHostToMachine
	err := db.Where(&filter).Find(&hostToMachines).Error
	if err != nil && err == gorm.ErrRecordNotFound {
		return nil, errors.WithStack(err)
	}
	return hostToMachines, nil
}
